const express =require("express");
const app =express();
const mysql=require("mysql");


const db =mysql.createConnection({
    host:"192.168.76.35",
    user:"root",
    password:"root",
    database:"bike"
}) 

db.connect((err)=>{
    if(err) throw err;
    console.log("连接成功");
})

setInterval(()=>{
    db.ping((err)=>{
        console.log("数据库 ping error"+JSON.stringify(err))
    })
    console.log("心跳连接数据库!")
},600000);

app.listen(8020,()=>{
    console.log("服务器开启在8020端口")
})

app.get("/getdatas",(req,res)=>{
    console.log(req)
    if(req.query.name!=undefined&&req.query.mintime!=undefined&&req.query.maxtime!=undefined){
        let sql="SELECT * FROM bike.bikedata where name='"+req.query.name+"' and revtime > "+req.query.mintime+" and revtime < "+req.query.maxtime;
        db.query(sql,(err,result)=>{
            if(err){
                console.log(err);
            }else{
                console.log(result);
                res.send(result)
            }
        })
    }
    else{
        res.send("参数有误!")
    }
})

app.get("/getlastdatas",(req,res)=>{
    console.log(req)
    if(req.query.name!=undefined){
        let sql="SELECT * FROM bike.bikedata where name='"+req.query.name+"' order by revtime desc limit 0,9";
        db.query(sql,(err,result)=>{
            if(err){
                console.log(err);
            }else{
                console.log(result);
                res.send(result)
            }
        })
    }
    else{
        res.send("参数有误!")
    }
})



//查询用户数据
app.get("/getUserdatas",(req,res)=>{
    let key;
    console.log(req.query)
    // console.log(req.query.name)
    //条件判断可更改，判断前端是否有登录验证查询
    if(req.query.name!=null&&req.query.password!=null){
        let sql="SELECT * FROM bike.user";
        db.query(sql,(err,result)=>{
            if(err){
                console.log(err);
            }else{
                console.log(result);
                // console.log(result[0].name);
                // console.log(result[0].password);
                for(let i = 0; i < result.length; i++){
                    if(req.query.name==result[i].name && req.query.password==result[i].password){
                        key = "1";
                        break;
                    }else{
                        key="0";
                    }
                }
                console.log(key);
                res.send(key)
            }
        })
    }
    else{
        res.send("参数有误!")
    }
})


//用户注册
app.get("/addUser",(req, res)  => {
    if(req.query.name!=undefined){
        let sql = "insert into bike.user (name,password) values (?,?)";
        db.query(sql, [req.query.name, req.query.password] ,(err, result) => {
            if(err){
                console.log(err)
            } else{
                console.log("添加用户数据成功！")
                res.send(result)
            }
        })
    }
    else{
        res.send("参数有误!")
    }
})